<template>
  <div class="market-tabs">
    <div class="tabs-nav" ref="tabsNav">
      <div 
        class="tabs-nav-wrap" 
        ref="tabsNavWrap"
        @touchstart="handleNavTouchStart"
        @touchmove="handleNavTouchMove"
        @touchend="handleNavTouchEnd"
      >
        <div 
          v-for="(tab, index) in tabs" 
          :key="index"
          class="tab-item"
          :class="{ active: value === tab.id }"
          @click="handleTabClick(tab.id)"
        >
          <span class="tab-text">{{ tab.text }}</span>
          <span v-if="tab.badge" class="tab-badge">{{ tab.badge }}</span>
        </div>
      </div>
      <div class="tabs-line" :style="lineStyle"></div>
    </div>
    <div 
      class="tabs-content" 
      ref="content"
      @touchstart="handleContentTouchStart"
      @touchmove="handleContentTouchMove"
      @touchend="handleContentTouchEnd"
    >
      <div 
        class="tabs-track"
        ref="track"
        :style="{ transform: `translateX(${contentOffset}px)` }"
      >
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MarketTabs',
  props: {
    value: {
      type: [String, Number],
      default: 1
    },
    tabs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      touchStartX: 0,
      touchStartY: 0,
      touchDeltaX: 0,
      touchDeltaY: 0,
      transformX: 0,
      lineWidth: 20,
      lineLeft: 0,
      contentOffset: 0,
      contentTouchStartX: 0,
      contentStartOffset: 0,
      isDragging: false
    }
  },
  computed: {
    lineStyle() {
      return {
        width: `${this.lineWidth}px`,
        transform: `translateX(${this.lineLeft}px)`,
        transition: 'transform 0.3s'
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        this.$nextTick(() => {
          this.scrollToTab(val)
        })
      },
      immediate: true
    }
  },
  methods: {
    handleTabClick(tabId) {
      this.$emit('input', tabId)
      this.$emit('change', tabId)
      this.$nextTick(() => {
        this.updateLine()
        this.scrollIntoView()
      })
    },
    handleNavTouchStart(e) {
      const touch = e.touches[0]
      this.touchStartX = touch.clientX
      this.touchStartY = touch.clientY
      this.touchDeltaX = 0
      this.touchDeltaY = 0
    },
    handleNavTouchMove(e) {
      const touch = e.touches[0]
      this.touchDeltaX = touch.clientX - this.touchStartX
      this.touchDeltaY = touch.clientY - this.touchStartY

      if (Math.abs(this.touchDeltaX) > Math.abs(this.touchDeltaY)) {
        e.preventDefault()
        e.stopPropagation()

        const newTransform = this.transformX + this.touchDeltaX
        const maxTransform = 0
        const minTransform = this.$refs.tabsNav.offsetWidth - this.$refs.tabsNavWrap.offsetWidth

        if (newTransform <= maxTransform && newTransform >= minTransform) {
          this.$refs.tabsNavWrap.style.transform = `translateX(${newTransform}px)`
        }
      }
    },
    handleNavTouchEnd() {
      this.transformX += this.touchDeltaX
      this.transformX = Math.min(0, Math.max(this.transformX, 
        this.$refs.tabsNav.offsetWidth - this.$refs.tabsNavWrap.offsetWidth))
    },
    updateLine() {
      const activeTab = this.$refs.tabsNavWrap.children[this.tabs.findIndex(tab => tab.id === this.value)]
      if (activeTab) {
        this.lineLeft = activeTab.offsetLeft + (activeTab.offsetWidth - this.lineWidth) / 2
      }
    },
    scrollIntoView() {
      const activeTab = this.$refs.tabsNavWrap.children[this.tabs.findIndex(tab => tab.id === this.value)]
      if (!activeTab) return

      const navWidth = this.$refs.tabsNav.offsetWidth
      const tabLeft = activeTab.offsetLeft
      const tabWidth = activeTab.offsetWidth

      let scrollLeft = tabLeft - (navWidth - tabWidth) / 2
      const maxScroll = this.$refs.tabsNavWrap.offsetWidth - navWidth
      scrollLeft = Math.max(Math.min(scrollLeft, maxScroll), 0)

      this.$refs.tabsNavWrap.style.transform = `translateX(${-scrollLeft}px)`
      this.transformX = -scrollLeft
    },
    handleContentTouchStart(e) {
      const touch = e.touches[0]
      this.contentTouchStartX = touch.clientX
      this.contentStartOffset = this.contentOffset
      this.isDragging = true
    },
    handleContentTouchMove(e) {
      if (!this.isDragging) return
      
      const touch = e.touches[0]
      const deltaX = touch.clientX - this.contentTouchStartX
      const newOffset = this.contentStartOffset + deltaX
      
      // 计算最大可滚动距离
      const contentWidth = this.$refs.content.offsetWidth
      const trackWidth = this.$refs.track.offsetWidth
      const maxOffset = 0
      const minOffset = -(trackWidth - contentWidth)
      
      // 限制滑动范围
      if (newOffset <= maxOffset && newOffset >= minOffset) {
        this.contentOffset = newOffset
      }
    },
    handleContentTouchEnd() {
      if (!this.isDragging) return
      
      const contentWidth = this.$refs.content.offsetWidth
      const deltaX = this.contentOffset - this.contentStartOffset
      
      // 判断滑动方向和距离
      if (Math.abs(deltaX) > contentWidth * 0.3) {
        const currentIndex = this.tabs.findIndex(tab => tab.id === this.value)
        let newIndex = currentIndex
        
        if (deltaX > 0 && currentIndex > 0) {
          // 向右滑动，切换到上一个tab
          newIndex = currentIndex - 1
        } else if (deltaX < 0 && currentIndex < this.tabs.length - 1) {
          // 向左滑动，切换到下一个tab
          newIndex = currentIndex + 1
        }
        
        // 切换到新的tab
        this.$emit('input', this.tabs[newIndex].id)
        this.$emit('change', this.tabs[newIndex].id)
      }
      
      // 重置位置到当前激活的tab
      this.scrollToTab(this.value)
      this.isDragging = false
    },
    scrollToTab(tabId) {
      const index = this.tabs.findIndex(tab => tab.id === tabId)
      const contentWidth = this.$refs.content.offsetWidth
      this.contentOffset = -index * contentWidth
      
      // 更新导航栏位置
      this.updateLine()
      this.scrollIntoView()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.updateLine()
      this.scrollIntoView()
    })
  }
}
</script>

<style lang="scss" scoped>
.market-tabs {
  width: 100%;
  overflow: hidden;
  
  .tabs-nav {
    position: relative;
    width: 100%;
    height: 44px;
    background: var(--tab-nav-background, #1a1a1a);
    overflow: hidden;
    
    .tabs-nav-wrap {
      display: flex;
      height: 100%;
      transition: transform 0.3s ease;
      
      .tab-item {
        flex: none;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 16px;
        font-size: 14px;
        color: var(--tab-text-color, #999);
        cursor: pointer;
        white-space: nowrap;
        
        .tab-text {
          position: relative;
          line-height: 44px;
        }
        
        &.active {
          color: var(--tab-active-color, #fff);
          font-weight: 500;
        }
        
        .tab-badge {
          position: absolute;
          top: 8px;
          right: 0;
          min-width: 16px;
          height: 16px;
          padding: 0 4px;
          font-size: 12px;
          line-height: 16px;
          text-align: center;
          background: var(--badge-background, #ff4d4f);
          color: #fff;
          border-radius: 8px;
          transform: translateX(50%);
        }
      }
    }
    
    .tabs-line {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 2px;
      background: var(--tab-active-line-color, #fff);
      border-radius: 1px;
    }
  }

  .tabs-content {
    position: relative;
    overflow: hidden;
    
    .tabs-track {
      display: flex;
      width: 100%;
      height: 100%;
      transition: transform 0.3s ease;
      
      > * {
        flex: none;
        width: 100%;
      }
    }
  }
}
</style>
